<?php
!defined('P_W') && exit('Forbidden');

class PW_House_SecondPostDB extends BaseDB {
	var $_tableName = "pw_house_secondpost";
	var $_primaryKey = 'uid';
	
	/**
	 * 获取单条数据
	 */
	function get($uid) {
		$temp = $this->_get($uid);
		return $temp;
	}
	/**
	 * 更新某条数据
	 * @param $fieldData
	 * @param $groupid
	 */
	function update($fieldData,$uid) {
		return $this->_update($fieldData,$uid);
	}
	/**
	 * 删除一条数据
	 * @param $groupid
	 */
	function delete($uid) {
		return $this->_delete($uid);
	}
	/**
	 * 添加一条数据
	 * @param $fieldData
	 */
	function insert($fieldData) {
		return $this->_insert($fieldData);
	}
	/**
	 * 添加或减少salenum的数量
	 * @param $uid
	 * @param $num
	 */
	function addSalenum($uid,$num = 1,$ifbroker = 0) {
		return $this->_updateSecondNum('salenum',$uid,$num,$ifbroker);
	}
	/**
	 * 添加或减少hirenum的数量
	 * @param $uid
	 * @param $num
	 */
	function addHirenum($uid,$num = 1,$ifbroker = 0) {
		return $this->_updateSecondNum('hirenum',$uid,$num,$ifbroker);
	}
	
	function _updateSecondNum($type,$uid,$num,$ifbroker = 0) {
		$uid = (int) $uid;
		$num = (int) $num;
		$ifbroker = (int) $ifbroker;
		if (!in_array($type,array('salenum','hirenum')) || !$uid) return false;
		$temp = $this->get($uid);
		if (!$temp) $this->insert(array("uid"=>$uid,"ifbroker"=>$ifbroker));
		
		$num = (int) $num;
		$_sqlAdd = '';
		if ($num<0) {
			if ($temp[$type] < abs($num)) return $this->update(array("$type"=>0),$uid);
		} else {
			$_sqlAdd = $this->_getAddSqlForAdd($type,$num);
		}
		$_sql = 'UPDATE '.$this->_tableName." SET $type=$type+".pwEscape($num)."$_sqlAdd WHERE uid=".pwEscape($uid);
		return $this->_db->update($_sql);
	}
	
	function _getAddSqlForAdd($type,$num) {
		global $timestamp;
		$num = (int) $num;
		if (!in_array($type,array('salenum','hirenum')) || $num<1) return '';
		
		if ($type == 'salenum') {
			return ',todaysalenum=todaysalenum+'.pwEscape($num).',lastsaletime='.pwEscape($timestamp);
		}
		if ($type == 'hirenum') {
			return ',todayhirenum=todayhirenum+'.pwEscape($num).',lasthiretime='.pwEscape($timestamp);
		}
	}
	function getStruct() {
		return array('uid','salenum','hirenum','todaysalenum','lastsaletime','todayhirenum','lasthiretime');
	}

}